/*
  学习目标：聊天消息发送-优化
  1. 不允许为空
  2. 监听回车，发送消息
*/
import Icon from '@/components/Icon';
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';

import io, { Socket } from 'socket.io-client';
import { baseURL } from './../../../utils/request';
import { getToken } from '@/utils/storage';
import { Toast } from 'antd-mobile';

type ChatMsgType = {
  type: string;
  msg: string;
  timestamp: number;
};

export default function Chat() {
  const [msg, setMsg] = useState('');
  const [msgList, setMsgList] = useState<ChatMsgType[]>([]);

  const clientRef = useRef<Socket | null>(null);

  useEffect(() => {
    clientRef.current = io(baseURL, {
      query: {
        token: getToken().token,
      },
      transports: ['websocket'],
    });

    clientRef.current.on('connect', () => {
      setMsgList([{ msg: '你好，小智为你服务', type: 'robot', timestamp: Date.now() }]);
    });

    clientRef.current.on('message', (data) => {
      console.log('data  ----->  ', data);
      // 💥 使用回调函数的更新方式去更新list
      setMsgList((preList) => {
        return [...preList, { ...data, type: 'robot' }];
      });
    });

    return () => {
      clientRef.current?.close();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSendMsg = () => {
    // 1.
    if (msg.trim()) {
      const userMsg = { msg, timestamp: Date.now() };
      clientRef.current?.emit('message', userMsg);
      setMsgList([...msgList, { ...userMsg, type: 'user' }]);
      setMsg('');
    } else {
      Toast.show({ content: '不能发送空消息' });
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSendMsg();
    }
  };

  useEffect(() => {
    window.scrollTo({
      top: document.body.scrollHeight,
      behavior: 'smooth',
    });
  }, [msgList]);

  return (
    <div className={styles.root}>
      <NavBar fixed>小智同学</NavBar>

      <div className="chat-list">
        {msgList.map((item) => {
          return item.type === 'robot' ? (
            <div className="chat-item" key={item.timestamp}>
              <Icon type="iconbtn_xiaozhitongxue" />
              <div className="message">{item.msg}</div>
            </div>
          ) : (
            <div className="chat-item user" key={item.timestamp}>
              <div className="message">{item.msg}</div>
            </div>
          );
        })}
      </div>

      <div className="footer">
        <div className="input-footer">
          <Input
            className="no-border"
            placeholder="请描述您的问题"
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
            onKeyDown={(e) => handleKeyDown(e)}
          />
          <Icon type="iconbianji" />
          <span className="send" onClick={handleSendMsg}>
            发送
          </span>
        </div>
      </div>
    </div>
  );
}
